<?php
class User extends AppModel {
	var $name = 'User';
	var $displayField = 'username';
	
	var $validate = array(
		
		

		'username' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'isUnique'=>array(
        		'rule' => array('isUnique'),
	        	'message' => 'Name already in use.'
    		)
		),
	
		'dob' => array(
			'date' => array(
				'rule' => array('date'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'address' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'mobile' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'email' => array(
			'email' => array(
				'rule' => array('email'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'isUnique'=>array(
        		'rule' => array('isUnique'),
	        	'message' => 'Email already in use.'
    		)
		),
		'degree' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'university' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);
    
   	var $hasMany = array(
		'UserRole' => array(
			'className' => 'UserRole',
			'foreignKey' => 'user_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		)
	);

/*
	function identicalFieldValues( $field=array(), $compare_field=null ) 
    {
        foreach( $field as $key => $value ){
            $v1 = $value;
            $v2 = $this->data[$this->name][ $compare_field ];                 
            if($v1 !== $v2) {
                return FALSE;
            } else {
                continue;
            }
        }
        return TRUE;
    } 
	
    function beforeSave($options)
    {
        $this->data['User']['password'] = md5($this->data['User']['password']);
        $this->data['User']['confirm_password'] = md5($this->data['User']['confirm_password']);
        return true;
    }
    
    function afterSave($created)
    {
        if($created){
            //member as default
            $data['UserRole']['user_id'] = $this->id;
            $data['UserRole']['role_id'] = 2;
            $this->UserRole->save($data);  
            
            if(isset($this->data['User']['roles']) && $this->data['User']['roles']!='1' && $this->data['User']['roles']!='2')
            {
                $this->UserRole->create();
                $data['UserRole']['user_id'] = $this->id;
                $data['UserRole']['role_id'] = $this->data['User']['roles'];
                $this->UserRole->save($data);               
            }          
        }
    }
   
 */
    
    function login($type,$username,$password)
    {        
        if($type=='username')
        {
            $data = $this->loginByUsername($username,$password);
        }
        elseif ($type == 'email')
        {
            $data = $this->loginByEmail($username,$password);
        }
        else
        {
            $data = $this->loginByBoth($username,$password);
        }
        if($data)
        {
            $data['permissions'] = $this->getAllPermissions($data['User']['id']);
            return $data;
        }
        return false;
    }
	
	function loginByUsername($username,$password)
	{
		return $this->find('first', array('conditions'=>array('User.username'=>$username,'User.password'=>md5($password))));
	}
	
	function loginByEmail($email,$password)
	{
		return $this->find('first',array('conditions'=>array('User.email'=>$email,'User.password'=>md5($password))));
	}
	
	function loginByBoth($username,$password)
	{
		return $this->find('first',array('conditions'=>array("OR"=>array('User.email'=>$username,'User.username'=>$username), 'User.password'=>md5($password))));
	}
    
    function getAllPermissions($user_id)
    {
        App::import('Model', 'Permission');
        $permissionModel = new Permission();
        App::import('Core', 'ConnectionManager');
        $dataSource = ConnectionManager::getDataSource('default');
        $prefix = $dataSource->config['prefix'];
        
        $options['joins'] = array(
             array(
             'table' => $prefix.'role_permissions',
             'alias' => 'RolePermission',
             'type' => 'inner',
             'conditions' => array('Permission.id = RolePermission.permission_id')
             )
         );        
        //$records =  $permissionModel->query('SELECT p.name FROM permissions p INNER JOIN role_permissions rp ON p.id = rp.permission_id INNER JOIN user_roles ur ON rp.role_id = ur.role_id AND ur.user_id ="'.$user_id.'" GROUP BY p.name ');
        $records = $permissionModel->find('all',$options);        
        $data = array();
        foreach($records as $record)
        {
            $data[] = $record['Permission']['name'];
        }        
        return $data;
    }
	
	function changeTestStatus($userId,$status='failed')
	{
		return $this->updateAll(array('User.test_status'=>'"'.$status.'"'),array('User.id'=>$userId));
	}
	
	function changePassword($userId, $password)
	{
		return $this->updateAll(array('User.password'=>'"'.md5($password).'"'),array('User.id'=>$userId));
	}
}
